﻿using Bootstrap.Security.Authorization;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Mvc.Filters
{
    /// <summary>
    /// 按钮权限检查过滤器
    /// </summary>
    public class ButtonAuthorizeAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 按钮授权所属菜单
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        /// 按钮授权标识码
        /// </summary>
        public string Auth { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var buttonAuthorizateSvr = context.HttpContext.RequestServices.GetRequiredService<IButtonAuthorization>();
            if (buttonAuthorizateSvr == null || !buttonAuthorizateSvr.Authorizate(context.HttpContext, Url, Auth))
            {
                context.Result = new UnauthorizedResult();
            }
            return base.OnActionExecutionAsync(context, next);
        }
    }
}
